package com.yorick.netty.messageListener;

import io.netty.channel.ChannelHandlerContext;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Register {

    private static Register instance = new Register();

    private final static String BASE_PACKAGE = "com.yorick.logic.service.%s";

    public  Map<Integer, String> map = new HashMap<>();
    public  Map<Integer, Object> objectMap = new HashMap<>();
    public  Map<Integer, Method> methodMap = new HashMap<>();

    private Register(){}

    public static Register getInstance(){
        return instance;
    }

    public void invoke(){
        try {
            for (Map.Entry<Integer, String> entry : map.entrySet()) {
                Class c = Class.forName(String.format(BASE_PACKAGE, entry.getValue()));
                Object obj = c.newInstance();
                Method method = c.getDeclaredMethod("task", new Class[] {byte[].class, ChannelHandlerContext.class});
                objectMap.put(entry.getKey(),obj);
                methodMap.put(entry.getKey(), method);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  void registerMessage(int msgId, String serviceName){
        map.put(msgId, serviceName);
    }
}
